<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:classify:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:classify:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:classify:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:classify:export']"
        >导出</el-button>
      </el-col>
    </el-row>

    <el-table
      v-loading="loading"
      :data="newClassifyList"
      row-key="classifyId"
      @selection-change="handleSelectionChange"
      :default-expand-all="false"
      :indent="30"
      :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="classifyId" />
      <el-table-column label="分类名称" align="center" prop="classifyName" />
      <el-table-column label="分类图片" align="center" prop="classifyImg" >
        <template slot-scope="{row}">
          <el-image
            class="classify-image"
            :src="row.classifyImg"
            :preview-src-list="[row.classifyImg]"
            fit="contain"
          >
            <div slot="error">
              <i class="el-icon-document" />
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="顺序" align="center" prop="indexSort" />
      <el-table-column label="菜单等级" align="center" prop="rank" />
      <el-table-column label="父菜单Id" align="center" prop="parentId" />
      <el-table-column label="首页显示" align="center" prop="indexShow" :formatter="indexShowFormat"/>
      <el-table-column label="菜单状态" align="center" prop="visible" :formatter="visibleFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:classify:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:classify:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改商品分类信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="分类名称" prop="classifyName">
          <el-input v-model="form.classifyName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="分类等级" prop="classifyName">
          <el-input v-model="form.rank" placeholder="请输入分类等级" />
        </el-form-item>
        <el-form-item label="父菜单Id" prop="classifyName">
          <el-input v-model="form.parentId" placeholder="请输入父菜单Id(一级菜单为0)" />
        </el-form-item>
        <el-form-item label="分类图片">
          <el-upload
            :action="commonUploadApi"
            :accept="'.png,.jpg'"
            :file-list="fileList"
            :headers="headers"
            :before-remove="handleBeforeRemove"
            :on-success="handleSuccess"
            :on-error="handleError"
            :limit="1"
            list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="顺序" prop="indexSort">
          <el-input-number v-model="form.indexSort" placeholder="请输入顺序" controls-position="right" :min="0"/>
        </el-form-item>
        <el-form-item label="是否活动" prop="isActivity">
          <el-radio-group v-model="form.isActivity">
            <el-radio
              v-for="dict in activityOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示状态" prop="visible">
          <el-radio-group v-model="form.visible">
            <el-radio
              v-for="dict in visibleOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="首页显示" prop="indexShow">
          <el-radio-group v-model="form.indexShow">
            <el-radio
              v-for="dict in visibleOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>


        <el-form-item label="是否特殊" prop="isSpecial">
          <el-radio-group v-model="form.isSpecial">
            <el-radio
              v-for="dict in specialOptions"
              :key="dict.dictValue"
              :label="dict.dictValue"
            >{{dict.dictLabel}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-row v-if="form.isSpecial == 1">
          <el-form-item label="特殊类型" prop="isReturn">
            <el-radio-group v-model="form.isReturn">
              <el-radio
                v-for="dict in isReturns"
                :key="Number(dict.dictValue)"
                :label="Number(dict.dictValue)"
              >{{dict.dictLabel}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="地址" prop="arg" v-if="form.isReturn == 2">
            <el-input  placeholder="arg"  v-model="form.arg" />
          </el-form-item>
          <el-form-item label="arg" prop="arg" v-if="form.isReturn == 1">
            <el-input  placeholder="arg"  v-model="form.arg" />
          </el-form-item>
          <el-form-item label="code" prop="code" v-if="form.isReturn == 1">
            <el-input  placeholder="code" v-model="form.code"/>
          </el-form-item>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listClassify,
  getClassify,
  delClassify,
  addClassify,
  updateClassify,
  exportClassify,
  delGoodsLowerClassify,
} from "@/api/system/classify";
import {mapGetters} from "vuex";
import { getToken } from "@/utils/auth";

export default {
  name: "Classify",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 商品分类信息表格数据
      classifyList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        classifyName: undefined,
        classifyImg: undefined,
        indexSort: undefined,
        indexShow: undefined,
        visible: undefined,
        parentId: undefined,
        rank: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        classifyName: [
          { required: true, message: "分类名称不能为空", trigger: "blur" }
        ],
        classifyImg: [
          { required: true, message: "分类图片不能为空", trigger: "blur" }
        ],
        indexSort: [
          { required: true, message: "顺序不能为空", trigger: "blur" }
        ],
        indexShow: [
          { required: true, message: "首页显示不能为空", trigger: "blur" }
        ],
        visible: [
          { required: true, message: "显示状态不能为空", trigger: "blur" }
        ],
        isSpecial: [
          { required: true, message: "特殊分类未选", trigger: "blur" }
        ],
        parentId: [
          { required: true, message: "父级菜单id不能为空", trigger: "blur" }
        ],
        rank: [
          { required: true, message: "菜单等级不能为空", trigger: "blur" }
        ],
      },
      // 显示状态数据字典
      specialOptions: [
        {
          dictValue: 0,
          dictLabel: '否'
        },
        {
          dictValue: 1,
          dictLabel: '是'
        }
      ],
      activityOptions: [
        {
          dictValue: '20',
          dictLabel: '否'
        },
        {
          dictValue: '10',
          dictLabel: '是'
        }
      ],
      visibleOptions: [],
      fileListLower : [],
      fileListLower2 : [],
      // 显示状态数据字典
      isReturns: [],
      fileList: [],
      headers: { Authorization: "Bearer " + getToken() },
    };
  },
  computed: {
    ...mapGetters([
      'commonUploadApi'
    ]),

    newClassifyList() {
      let arr = []
      let arrSecond = []
      this.classifyList.forEach((item) => {
        if(item.parentId == 0) {
          arr.push(item)
        } else {
          arrSecond.push(item)
        }
      })
      arr.forEach((item) => {
        item.children = []
        arrSecond.forEach((item2) => {
          if(item2.parentId == item.classifyId) {
            item.children.push(item2)
          }
        })
      })
      return arr
    }
  },
  created() {
    this.getList();
    this.getDicts("sys_show_hide").then(response => {
      this.visibleOptions = response.data;
    });
    this.getDicts("sys_is_return").then(response => {
      this.isReturns = response.data;
    });
  },
  methods: {
    /** 查询商品分类信息列表 */
    getList() {
      this.loading = true;
      listClassify(this.queryParams).then(response => {
        this.classifyList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    changeImgCode(code) {

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        classifyId: undefined,
        classifyName: undefined,
        classifyImg: undefined,
        indexSort: undefined,
        indexShow: '1',
        visible: '0',
        createTime: undefined,
        updateTime: undefined,
        createBy: undefined,
        updateBy: undefined,
        parentId: undefined,
        rank: undefined,
        isReturn: undefined,
        isSpecial: '0',
        isActivity: '20',
        uri:"",
        code:"",
        lowerClassImg:undefined,
        uriSecond:"",
        codeSecond:"",
        lowerClassImgSecond:undefined,
        changeImgCode:"",
        goodsClassifyOtherId: "",
        goodsClassifyOtherId2: "",
      };
      this.fileList = [];
      this.fileListLower = [];
      this.fileListLower2 = [];
      this.lowerClassDTO={};
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.classifyId)
      this.single = selection.length!=1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品分类信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const classifyId = row.classifyId || this.ids
      getClassify(classifyId).then(response => {
        this.form = response.data;
        this.fileList.push({ url:response.data.classifyImg });
        this.open = true;
        this.title = "修改商品分类信息";
      });
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.classifyId != undefined) {
            updateClassify(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addClassify(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const classifyIds = row.classifyId || this.ids;
      this.$confirm('是否确认删除商品分类信息编号为"' + classifyIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delClassify(classifyIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function() {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有商品分类信息数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportClassify(queryParams);
      }).then(response => {
        this.download(response.data);
      }).catch(function() {});
    },
    handleSuccess(response, file, fileList){
      this.form.classifyImg = response.url;
    },
    handleSuccessLower(response, file, fileList){
      this.form.lowerClassImg =response.url;
    },
    handleSuccessLowerSecond(response, file, fileList){
      this.form.lowerClassImgSecond = response.url;
    },
    // 监听上传失败
    handleError(e, file, fileList) {
      const msg = JSON.parse(e.message);
      this.msgError(msg.message);
    },
    handleBeforeRemove(file, fileList) {
      this.form.classifyImg= null;
    },
    handleBeforeRemoveLower(file, fileList) {
      delGoodsLowerClassify(this.form.goodsClassifyOtherId)
      this.form.goodsClassifyOtherId=''
    },
    handleBeforeRemoveLowerSecond(file, fileList) {
      delGoodsLowerClassify(this.form.goodsClassifyOtherId2)
      this.form.goodsClassifyOtherId=''
    },
    // 显示状态字典翻译
    indexShowFormat(row, column) {
      return this.selectDictLabel(this.visibleOptions, row.indexShow);
    },
    // 菜单状态字典翻译
    visibleFormat(row, column) {
      return this.selectDictLabel(this.visibleOptions, row.visible);
    },
  }
};
</script>
<style>
.classify-image > img{
  width: 50px;
  height: 50px;
}
</style>
